<?php
ob_start();
$mid="";
$rid="";
// filter the URL for keys
    foreach($_GET as $key => $value) {
		if($key == "mid") {$mid = $value;}
		elseif($key == "rid") {$rid = $value;}
	}
	$db = mysql_connect("mysql513.in.shared-server.net:16033", "JRtu434", "qvoiceDB1");
	mysql_select_db("JRtu434", $db);
	//check if the monitor has a url yet
	$result = mysql_query("select id,url from tbl_url where rid='".$rid."' and mid='".$mid."'");
	
	if(!mysql_num_rows($result)){
		//retrieve the next unused URL
		$result = mysql_query("select id,url from tbl_url where rid='".$rid."' and mid is null limit 1");
		$res = mysql_fetch_array($result);
		$url = $res[1];
		$id = $res[0];
	}
	else {
		$res = mysql_fetch_array($result);
		$url = $res[1];
		$id = $res[0];
		//set the URL to used
	}
mysql_query("Update tbl_url set mid='".$mid."' where id='".$id."'");
//find the UID and other data.
$sql = "select * from testredirect where rid='" . $rid . "' and monID='" . $mid ."'and url='" . $url ."'";
$res = mysql_query($sql);
// if not found, insert values, but update if mid/rid pair exists
if(!mysql_num_rows($res)) {
	$res2 = mysql_query("select * from testredirect where rid='" . $rid . "' and monID='" . $mid ."'");
	if(!mysql_num_rows($res2)){
		mysql_query("INSERT INTO testredirect (monID,rid,url,start) VALUES ('".$mid."','".$rid."','".$url."','".time()."')");
		$res = mysql_query($sql);
		$item = mysql_fetch_array($res);
		$nurl = "http://www.q-voice.net/public/thanks/ssg/chuui.php?uid=". $item['ID'];
		}
		else{
		mysql_query("Update testredirect set url='$url' where monID='$mid' and rid='$rid'");
		$res = mysql_query($sql);
		$item = mysql_fetch_array($res);
		$nurl = "http://www.q-voice.net/public/thanks/ssg/chuui.php?uid=". $item['ID'];
		}
}
// if found, send along.
else
{
$res = mysql_query($sql);
$item = mysql_fetch_array($res);
$nurl = "http://www.q-voice.net/public/thanks/ssg/chuui.php?uid=". $item['ID'];
}
header("Location: " . $nurl);
mysql_close();
ob_flush();
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="ja">
<!-- ==== document header ==== -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>アンケート画面に移動します</title>
</head>
</html>